//
//  GameNewsViewController.m
//  课余时间
//
//  Created by zgr on 16/4/6.
//  Copyright © 2016年 张大少. All rights reserved.
//

#import "GameNewsViewController.h"
#import "GameNewsCollectionViewCell.h"
#import "RequestManager.h"
#import "GameNewsModel.h"
#import "UIView+SDAutoLayout.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "GameNewsDetailViewController.h"
#import "MJRefresh.h"
#import "SDCycleScrollView.h"
#import "UIImageView+WebCache.h"

@interface GameNewsViewController ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *modelArray;
@property (nonatomic,strong)UINavigationController *nav;
@property (nonatomic,strong)NSString *nextUrl;
@property (nonatomic,strong)NSString *UrlString;
@property (nonatomic,strong)GameNewsModel *liveModel;
@property (nonatomic,assign)NSInteger nextIndex;
@property (nonatomic,assign)NSInteger perIndex;

@end

@implementation GameNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _modelArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT - 50) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[GameNewsCollectionViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    [self.tableView addLegendHeaderWithRefreshingTarget: self refreshingAction:@selector(headAction)];

    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footAction)];
    
   
    // Do any additional setup after loading the view.
}

-(void)setViewControllerWithUrlSting:(NSInteger )PerIndex nextINdext:(NSInteger)nextIndex runString:(NSString *)runString
{
    _nextIndex = nextIndex;
    _perIndex = PerIndex;
    [self requestUrlWithString:runString];
    [self requestUrlWithString:[NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/c%ld_list_%ld.shtml",PerIndex,nextIndex]];
       
}


//===================================================================
// 设置轮播图
#pragma mark =================轮播图 =======================
-(UIView *)setHeaderViewWith:(NSArray *)titles imgs:(NSArray *)images;
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 200)];
    
    SDCycleScrollView *cycleScreollView = [SDCycleScrollView cycleScrollViewWithFrame:view.bounds delegate:self placeholderImage:nil];
    cycleScreollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScreollView.titlesGroup = titles;
    cycleScreollView.currentPageDotColor = [UIColor whiteColor];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScreollView.imageURLStringsGroup = images;
    });
    [view addSubview:cycleScreollView];
    
    return view;
}
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    GameNewsDetailViewController *detail = [[GameNewsDetailViewController alloc]init];
    if ([[_modelArray[index] article_url] hasPrefix:@"http:"])
    {
        detail.article_url = [_modelArray[index] article_url];
    }
    else{
        detail.article_url = [NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/%@?APP_BROWSER_VERSION_CODE=1&ios_version=859&imgmode=auto",[_modelArray[index] article_url]];
    }
    [self presentViewController:detail animated:YES completion:nil];
    
}
//===================================================================
// 刷新界面
#pragma mark ==================界面刷新 ===================
-(void)headAction
{
   
   // [_modelArray removeAllObjects];
//    _modelArray = [NSMutableArray array];
  //  [self requestUrlWithString:GAME_NEWS_RUNIMG];
   [self requestUrlWithString:[NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/c%ld_list_%ld.shtml",_perIndex,_nextIndex]];
    
    [self.tableView.header endRefreshing];
    
}
-(void)footAction
{
    [self requestUrlWithString:[NSString stringWithFormat:@"%@%@",GAME_NEWS_DETAIL,_nextUrl]];
    
    [self.tableView.footer endRefreshing];
    
}
//===================================================================
// 数据请求
#pragma mark ------------ 数据请求------------------------
-(void)requestUrlWithString:(NSString *)urlString
{
    
    
    
    NSMutableArray *test = [NSMutableArray array];
    [[[RequestManager alloc]init] requestWithUrl:urlString requestType:RequestTypeGet parDic:nil finish:^(NSData *data) {
        NSMutableArray *titles = [NSMutableArray array];
        NSMutableArray *images = [NSMutableArray array];
        
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        if (bigDic == nil) {
            
            _nextIndex += 1;
            [self requestUrlWithString:[NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/c%ld_list_%ld.shtml",_perIndex,_nextIndex]];
            return ;
        }
     //   NSLog(@"%@",bigDic);
        
        NSArray *listArray = [bigDic objectForKey:@"list"];
        
        NSArray *liveArray = [bigDic objectForKey:@"live"];
        for (NSDictionary *dataDic in listArray) {
            GameNewsModel *model = [[GameNewsModel alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_modelArray addObject:model];
            
            [test addObject:model];
            
            [titles addObject:model.title];
            [images addObject:model.image_url_big];
        }
        
       _liveModel = [[GameNewsModel alloc]init];
    
        for (NSDictionary *liveDic in liveArray) {
            
            [_liveModel setValuesForKeysWithDictionary:liveDic];
            
        }
        if ([urlString isEqualToString:[NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/c%ld_list_%ld.shtml",_perIndex,_nextIndex]]) {
            
           // NSLog(@"-----%@ =+++++%@",_modelArray,test);
            if (test != nil) {
                _modelArray = test ;
            }
        }
        _nextUrl = [bigDic objectForKey:@"next"];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if ([urlString isEqualToString:@"http://qt.qq.com/php_cgi/lol_mobile/gamecenter/varcache_gamecenterindex.php?plat=ios&version=9663&a1=qtapp&a2="]) {
                if (_liveModel.LiveUrl != nil) {
                    _tableView.tableHeaderView = [self setCompetitionWith:_liveModel];
                }
            }
            if ([urlString isEqualToString:GAME_NEWS_RUNIMG]) {
                UIView *headView = [self setHeaderViewWith:titles imgs:images];
                _tableView.tableHeaderView = headView;
            }
            

            
          [_tableView reloadData];
        });
    } error:^(NSError *error) {
        
    }];
    
    
}
#pragma mark ============== 赛事的透视图 =============
-(UIView *)setCompetitionWith:(GameNewsModel *)model
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 200)];
    UILabel *sGamename = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, KWIDTH - 10, 20)];
 
    sGamename.text = model.sGameName;
    
    UIImageView *backImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 30, KWIDTH, 170)];
    [backImg sd_setImageWithURL:[NSURL URLWithString:model.videoImg]];
    UIImageView *videoImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 30, KWIDTH -100, 170)];
    videoImg.layer.cornerRadius = 5;
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH - 100, 30, 100, 170)];
    rightView.backgroundColor = [UIColor grayColor];
    rightView.alpha = 0.7;

    UILabel *date = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH - 100 + 10, 80, 80, 100)];
    date.numberOfLines = 0;
    date.text =  [NSString stringWithFormat:@"比赛时间：%@", [model.MatchDate substringFromIndex:5]];
    date.font = [UIFont boldSystemFontOfSize:15];
    date.textAlignment = NSTextAlignmentCenter;
    date.textColor = [UIColor whiteColor];
    UILabel *match = [[UILabel alloc]initWithFrame:CGRectMake(10, 170, KWIDTH - 100 - 10, 30)];
    match.text = model.bMatchName;
    match.textAlignment = NSTextAlignmentCenter;
    match.textColor = [UIColor whiteColor];
    [videoImg sd_setImageWithURL:[NSURL URLWithString:model.videoImg]];
    [view addSubview:backImg];
    [view addSubview: sGamename];
    [view addSubview:rightView];
    [view addSubview:videoImg];
    [view addSubview:date];
    [view addSubview:match];
    videoImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapA:)];
    [videoImg addGestureRecognizer:tap];
    
    return view;
}
-(void)tapA:(UITapGestureRecognizer *)tap
{
    GameNewsDetailViewController *detail = [[GameNewsDetailViewController alloc]init];
    NSLog(@"%@",_liveModel.LiveUrl);
    detail.article_url = _liveModel.LiveUrl;
    [self presentViewController:detail animated:YES completion:nil];
    
}


#pragma mark ====================

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GameNewsCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   // cell.backgroundColor = [UIColor redColor];
    GameNewsModel *model = _modelArray[indexPath.row];
   // [cell setCellWithModel:model];
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class currentClass = [GameNewsCollectionViewCell class];
    GameNewsModel *model = _modelArray[indexPath.row];
    
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:currentClass contentViewWidth:[self cellContentViewWith]];

}


- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GameNewsDetailViewController *detail = [[GameNewsDetailViewController alloc]init];
    
    if ([[_modelArray[indexPath.row] article_url] hasPrefix:@"http:"])
    {
        detail.article_url = [_modelArray[indexPath.row] article_url];
       
    }
                              else{
    detail.article_url = [NSString stringWithFormat:@"http://qt.qq.com/static/pages/news/phone/%@?APP_BROWSER_VERSION_CODE=1&ios_version=859&imgmode=auto",[_modelArray[indexPath.row] article_url]];
                              }
    
    [self presentViewController:detail animated:YES completion:nil];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
